package com.red.service.impl;

import com.red.mapper.UserMapper;
import com.red.pojo.Result;
import com.red.pojo.entity.User;
import com.red.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.util.List;

public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper mapper;

    public void setMapper(UserMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public int insertUser(User user) {
        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return mapper.addUser(user);
    }

    @Override
    public User selectUserByID(int id) {
        return mapper.selectUserByID(id);
    }

    @Override
    public User selectUserByAccount(String userName) {
        return mapper.selectUserByAccount(userName);
    }

    @Override
    public List<User> selectUserList(User user, int page, int size) {
        page = (page - 1) * size;
        return mapper.selectUserList(user, page, size);
    }

    @Override
    public int selectUserCount(User user) {
        return mapper.selectUserCount(user);
    }

    @Override
    public int deleteUserByID(int id) {
        return mapper.deleteUserByID(id);
    }

    @Override
    public int updateUser(User user) {
        return mapper.updateUser(user);
    }

    @Override
    public Result updateProfile(User user) {
        User nUser = new User();
        nUser.setUserId(user.getUserId());

        nUser.setUserName(user.getUserName());
        nUser.setEmail(user.getEmail());
        nUser.setBirthday(user.getBirthday());
        nUser.setSex(user.getSex());

        if (mapper.updateUser(nUser) > 0) {
            return Result.success();
        }

        return Result.error();
    }
}
